<template>
  <div class="article-list">
    <van-pull-refresh
      :success-text="refreshSuccessText"
      :success-duration="1500"
      v-model="isRefreshLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item";
export default {
  name: "ArticleList",
  components: {
    ArticleItem,
  },
  props: {
    //接收父组件传递过来的数据channel
    channel: {
      type: Object,
      required: true, //这个数据是必须的
    },
  },
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中loading状态
      finished: false, // 控制数据加载结束的状态
      error: false, // 是否加载失败
      timestamp: null, // 请求下一页数据的时间戳
      // 控制下拉刷新的失败状态
      isRefreshLoading: false,
      refreshSuccessText: "",
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });

        const { results } = data.data;
        // 数组合并
        this.list.push(...results);

        this.loading = false;
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true; // （显示没有更多）
        }
      } catch (err) {
        console.log("获取失败", err);
        this.loading = false; // 关闭locading效果
        this.error = true; // 开启错误提示
      }
    },

    // 当触发下拉菜单的时候调用该函数
    async onRefresh() {
      try {
        //1,请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1,
        });

        // 2, 将数据追加到列表顶部
        const { results } = data.data;
        this.list.unshift(...results);

        //3，关闭下拉刷新的locading状态
        this.isRefreshLoading = false;

        //4,更新下拉刷新成功提示的文本
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`;
      } catch (err) {
        console.log(err);
        this.isRefreshLoading = false;
        this.$toast("刷新失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
